<?php

namespace app\http;

use app\common\model\Company;
use app\common\model\Notice;
use app\common\model\Project;
use app\common\model\ProjectLog;
use app\common\model\Quest;
use app\common\model\User;
//require_once '/vendor/autoload.php';
// 导入要请求接口对应的Request类
// 导入可选配置类
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server {
	//protected $processes = 4;
	protected $socket = 'websocket://0.0.0.0:2003'; //正式
	//protected $socket = 'tcp://0.0.0.0:2008'; //测试
	/**
	 * 每个进程启动
	 * @param $worker
	 */
	public function onWorkerStart($worker) {
		Timer::add(1, array($this, 'quest'));
		// Timer::add(10, function () use ($worker) {
		// 	//添加心跳
		// 	foreach ($worker->connections as $connection) {
		// 		echo "connection-id = {$connection->id}\n";
		// 		$connection->send(1);
		// 	}
		// });

	}
	public function quest() {
		echo '[计划任务]--开始运行';
		echo "\r\n";
		$quest = Quest::where('id', 1)->findOrEmpty();
		if (!$quest->isEmpty()) {
			if ($quest['status'] == 1) {
				$project_list = Project::whereNotIn('status', [2, 3])->order('end_time', 'asc')->select()->toArray();

				foreach ($project_list as $key => $value) {
					if (time() >= strtotime($value['start_time']) && time() <= strtotime($value['end_time'])) {

						Project::where('id', $value['id'])->update(['status' => 1]);
					}
					if (time() >= strtotime($value['end_time'])) {
						$user_in_list = ProjectLog::where('project_id', $value['id'])->column('user_id'); //已投标用户
						$company_not_in_list = User::whereNotIn('id', $user_in_list)->column('company_id'); //未投标公司
						$param['cate'] = [$value['cate_id']];
						Company::scope('ApiWhere', $param)->whereIn('id', $company_not_in_list)->inc('not_open')->update();
						$lian_open = 1;

						$company_in_list = Company::scope('ApiWhere', $param)->whereIn('id', $company_not_in_list)->select(); //分类未投标公司
						foreach ($company_in_list as $kc => $vc) {
							$project2 = Project::where('cate_id', $value['cate_id'])->where('id', '<', $value['id'])->order('id', 'desc')->findOrEmpty();
							if (!$project2->isEmpty()) {
								$lian_open = 2;
								$project3 = Project::where('cate_id', $value['cate_id'])->where('id', '<', $project2['id'])->order('id', 'desc')->findOrEmpty();
								if (!$project3->isEmpty()) {
									Company::where('id', $vc['id'])->inc('lian_open')->update();
									$company1 = Company::where('id', $vc['id'])->findOrEmpty();
									if ($company1['lian_open'] >= 2) {
										Company::where('id', $vc['id'])->update(['lian_open' => 0]);
									}
									$company2 = Company::where('id', $vc['id'])->findOrEmpty();
									if ($company2['lian_open'] == 0) {
										//User::where('company_id', $vc['id'])->update(['status' => 0]);
										$company = Company::where('id', $vc['id'])->findOrEmpty();
										
									}

								}
							}
						}
						Project::where('id', $value['id'])->update(['status' => 2]);
						$project_log = ProjectLog::where('project_id', $value['id'])->select()->toArray();

						$result = $this->array_sort($project_log, 'all_money');
						// if ($value['win'] == 0) {

						// 	if (isset($result[2]) && $result[1]['all_money'] != $result[2]['all_money']) {
						// 		ProjectLog::where('id', $result[1]['id'])->update(['status' => 2]);
						// 		ProjectLog::where('project_id', $value['id'])->where('id', '<>', $result[1]['id'])->update(['status' => 1]);
						// 		$user = User::where('id', $result[1]['user_id'])->findOrEmpty();
						// 		if (!$user->isEmpty()) {
						// 			$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
						// 			$company = Company::where('id', $user['company_id'])->findOrEmpty();
						// 			if (!$company->isEmpty()) {
						// 				$notice_data = [
						// 					'title' => '恭喜' . $company['company_name'] . '中标',
						// 					'content' => '恭喜' . $company['company_name'] . '中标',
						// 				];
						// 				Notice::create($notice_data);
						// 			}

						// 		}

						// 	} else {
						// 		$project_log_like = ProjectLog::where('project_id', $value['id'])->where('all_money', $result[1]['all_money'])->order('id', 'asc')->select()->toArray();
						// 		ProjectLog::where('id', $project_log_like[0]['id'])->update(['status' => 2]);
						// 		ProjectLog::where('project_id', $value['id'])->where('id', '<>', $project_log_like[0]['id'])->update(['status' => 1]);
						// 		$user = User::where('id', $project_log_like[0]['user_id'])->findOrEmpty();
						// 		if (!$user->isEmpty()) {
						// 			$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
						// 			$company = Company::where('id', $user['company_id'])->findOrEmpty();
						// 			if (!$company->isEmpty()) {
						// 				$notice_data = [
						// 					'title' => '恭喜' . $company['company_name'] . '中标',
						// 					'content' => '恭喜' . $company['company_name'] . '中标',
						// 				];
						// 				Notice::create($notice_data);
						// 			}

						// 		}
						// 		// $mobile = [];
						// 		// foreach ($project_log_like as $lk => $lv) {
						// 		// 	$user = User::where('id', $lv['user_id'])->findOrEmpty();
						// 		// 	if (!$user->isEmpty()) {
						// 		// 		$mobile[] = $user['mobile'];
						// 		// 	}
						// 		// }
						// 		// $this->send_sms('2039667', [$value['title']], $mobile);
						// 	}
						// }
						if ($value['win'] == 0) {

							if (isset($result[1]) && $result[0]['all_money'] != $result[1]['all_money']) {
								ProjectLog::where('id', $result[0]['id'])->update(['status' => 2]);
								ProjectLog::where('project_id', $value['id'])->where('id', '<>', $result[0]['id'])->update(['status' => 1]);
								$user = User::where('id', $result[0]['user_id'])->findOrEmpty();
								if (!$user->isEmpty()) {
									$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
									$company = Company::where('id', $user['company_id'])->findOrEmpty();
									if (!$company->isEmpty()) {
										$notice_data = [
											'title' => '恭喜' . $company['company_name'] . '中标',
											'content' => '恭喜' . $company['company_name'] . '中标',
										];
										Notice::create($notice_data);
									}

								}

							} else {
								if (count($project_log) >= 1) {

									$project_log_like = ProjectLog::where('project_id', $value['id'])->where('all_money', $result[0]['all_money'])->order('id', 'asc')->select()->toArray();
									ProjectLog::where('id', $project_log_like[0]['id'])->update(['status' => 2]);
									ProjectLog::where('project_id', $value['id'])->where('id', '<>', $project_log_like[0]['id'])->update(['status' => 1]);
									$user = User::where('id', $project_log_like[0]['user_id'])->findOrEmpty();
									if (!$user->isEmpty()) {
										$this->send_sms('2039672', [$value['title']], [$user['mobile']]);
										$company = Company::where('id', $user['company_id'])->findOrEmpty();
										if (!$company->isEmpty()) {
											$notice_data = [
												'title' => '恭喜' . $company['company_name'] . '中标',
												'content' => '恭喜' . $company['company_name'] . '中标',
											];
											Notice::create($notice_data);
										}

									}
								}
								// $mobile = [];
								// foreach ($project_log_like as $lk => $lv) {
								// 	$user = User::where('id', $lv['user_id'])->findOrEmpty();
								// 	if (!$user->isEmpty()) {
								// 		$mobile[] = $user['mobile'];
								// 	}
								// }
								// $this->send_sms('2039667', [$value['title']], $mobile);
							}
						}
					}
				}

			}
		}

	}
	function array_sort($arr, $keys, $type = 'asc') {
		$keysvalue = $new_array = array();
		foreach ($arr as $k => $v) {
			$keysvalue[$k] = $v[$keys];
		}
		if ($type == 'asc') {
			asort($keysvalue);
		} else {
			arsort($keysvalue);
		}
		reset($keysvalue);
		foreach ($keysvalue as $k => $v) {
			$new_array[] = $arr[$k];
		}
		return $new_array;
	}
	public function searchsum($arr, $field) {
		if (!is_array($arr) || !$field) {
			return false;
		}

		$temp = array();
		foreach ($arr as $key => $val) {
			$temp[] = $val[$field];
		}

		return array_sum($temp);
	}
	public function send_sms($template_id, $param, $mobile) {
		try {

			$cred = new Credential("AKIDJTP8kHagXEi17zf6PUL4c4KRREmRzLUS", "Ii0BHOSQSPAsRtGUZZP3WwLpIerBTwc8");

			$httpProfile = new HttpProfile();

			$httpProfile->setReqMethod("GET"); // post请求(默认为post请求)
			$httpProfile->setReqTimeout(30); // 请求超时时间，单位为秒(默认60秒)
			$httpProfile->setEndpoint("sms.tencentcloudapi.com"); // 指定接入地域域名(默认就近接入)

			$clientProfile = new ClientProfile();
			$clientProfile->setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256)
			$clientProfile->setHttpProfile($httpProfile);

			$client = new SmsClient($cred, "ap-nanjing", $clientProfile);

			// 实例化一个 sms 发送短信请求对象,每个接口都会对应一个request对象。
			$req = new SendSmsRequest();

			/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
			// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
			$req->SmsSdkAppId = "1400880328";

			$req->SignName = "徐州恒清食品科技有限公司";

			$req->TemplateId = $template_id;

			$req->TemplateParamSet = $param;

			$req->PhoneNumberSet = $mobile;

			$resp = $client->SendSms($req);

			$result = $resp;

		} catch (TencentCloudSDKException $e) {
			echo $e;
		}

	}
	// public function onConnect($connection) {
	// 	$connection->send('连接成功');
	// 	echo "connection-id = {$connection->id}\n";
	// 	echo "new connection from ip " . $connection->id . "\n";
	// }

	// public function onMessage($connection, $data) {
	// 	if (isset($data)) {
	// 		$connection->id = $data;
	// 		$arr = json_decode($data, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 1]);
	// 		$connection->send($data);
	// 	}
	// }

	// public function onClose($connection) {
	// 	if (is_string($connection->id)) {
	// 		$arr = json_decode($connection->id, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 0]);
	// 	}
	// 	$connection->close();
	// 	echo "close-id = {$connection->id}\n";
	// }

	// public function onError($connection) //当客户端的连接上发生错误时触发
	// {
	// 	if (is_string($connection->id)) {
	// 		$arr = json_decode($connection->id, TRUE);
	// 		// db('user')->where("id", $arr['uid'])->update(['online' => 0]);
	// 	}
	// 	$connection->close();
	// 	echo "close-id = {$connection->id}\n";
	// }

}
